package com.zjw.forum.controller;

import com.sun.istack.internal.NotNull;
import com.zjw.forum.common.AppResult;
import com.zjw.forum.common.ResultCode;
import com.zjw.forum.dao.UserMapper;
import com.zjw.forum.exception.ApplicationException;
import com.zjw.forum.model.User;
import com.zjw.forum.services.IArticleReplyService;
import com.zjw.forum.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api("回复接口")
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IArticleReplyService articleReplayService;
    @PostMapping("/create")
    public AppResult create(HttpServletRequest httpServletRequest,
                            @NotNull @ApiParam("文章id") @RequestParam("articleId") Long articleId,
                            @NotNull @ApiParam("正文") @RequestParam("content") String content) {
        String user_token = httpServletRequest.getHeader("user_token");
        User userFromToken = JWTUtil.getUserFromToken(user_token);
        if(userFromToken==null){
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        //校验登陆用户是否正常（回复用户）
        User user = userMapper.selectByPrimaryKey(userFromToken.getId());
        if(user==null){
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(user.getState()==1){
            log.error(ResultCode.FAILED_USER_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        int i = articleReplayService.replyArticle(articleId, content, userFromToken.getId());
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return AppResult.success();
    }
    @GetMapping("/getReplies")
    public AppResult getReplies(@NotNull @ApiParam("文章id") @RequestParam("articleId") Long articleId){
        //从mybatis查询出来的集合不会为空，内容可能为空,所以不能判空
        return AppResult.success(articleReplayService.displayAllReply(articleId));
    }
}
